home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / java / io / example / Adler32.java < prev    next >
Encoding:
Java Source  |  1997-07-13  |  2.1 KB  |  73 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17. public
  18. class Adler32 implements Checksum {
  19.     private int value = 1;
  20.  
  21.     /*
  22.      * BASE is the largest prime number smaller than 65536
  23.      * NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
  24.      */
  25.     private static final int BASE = 65521;
  26.     private static final int NMAX = 5552;
  27.  
  28.     /**
  29.      * Update current Adler-32 checksum given the specified byte.
  30.      */
  31.     public void update(int b) {
  32.         int s1 = value & 0xffff;
  33.         int s2 = (value >> 16) & 0xffff;
  34.         s1 += b & 0xff;
  35.         s2 += s1;
  36.         value = ((s2 % BASE) << 16) | (s1 % BASE);
  37.     }
  38.  
  39.     /**
  40.      * Update current Adler-32 checksum given the specified byte array.
  41.      */
  42.     public void update(byte[] b, int off, int len) {
  43.         int s1 = value & 0xffff;
  44.         int s2 = (value >> 16) & 0xffff;
  45.  
  46.         while (len > 0) {
  47.             int k = len < NMAX ? len : NMAX;
  48.             len -= k;
  49.             while (k-- > 0) {
  50.                 s1 += b[off++] & 0xff;
  51.                 s2 += s1;
  52.             }
  53.             s1 %= BASE;
  54.             s2 %= BASE;
  55.         }
  56.         value = (s2 << 16) | s1;
  57.     }
  58.  
  59.     /**
  60.      * Reset Adler-32 checksum to initial value.
  61.      */
  62.     public void reset() {
  63.         value = 1;
  64.     }
  65.  
  66.     /**
  67.      * Returns current checksum value.
  68.      */
  69.     public long getValue() {
  70.         return (long)value & 0xffffffff;
  71.     }
  72. }
  73.